package com.yoga.manager.qrcodeUtil;

import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import com.yoga.manager.upyun.UploadChannelEnum;
import com.yoga.manager.upyun.UploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by guansheng on 2017/2/4.
 * 上传二维码图片并返回服务器地址
 */
public class UploadQrcodeUtil {

    private static String FOLDER=System.getProperty("java.io.tmpdir");

    private static Logger logger = LoggerFactory.getLogger(UploadQrcodeUtil.class);

    public static void  main(String[] arg) throws IOException, AppException {
        QRConfig qrConfig = new QRConfig();
        qrConfig = new QRConfig();
        qrConfig.setImageFormat("png");
        qrConfig.setWidth(120);
        qrConfig.setHeight(120);

        String url="https://www.baidu.com";
        String qrCodeUtl=doing(url, UploadChannelEnum.ORDER_SEND_QR_CODE, qrConfig);
        System.out.println(qrCodeUtl);
    }


    public  static String doing(String url,UploadChannelEnum channelEnum, QRConfig qRconfig
     ) throws AppException {
        Path path =Paths.get(FOLDER,System.currentTimeMillis()+".png");
        try {
         OutputStream outputStream = Files.newOutputStream(path);
         QrcodeUtils.genQrcode(url,qRconfig,outputStream);
         String qrcodeFile  = UploadUtils.imageUpload(channelEnum, path.toFile(),false);
         return qrcodeFile;
        } catch (IOException e) {
            logger.error("",e);
            throw new AppException(AppErrorCodeEnum.GEN_QR_CODE_ERROR,e);
        } catch (AppException e) {
            logger.error("",e);
            throw e;
        }finally {
            File file = path.toFile();
            if(file.exists()){
                path.toFile().delete();
            }
        }

    }
}
